#include <bits/stdc++.h>

using namespace std;


class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> ans;
        int rlen=matrix.size();
        if(rlen==0) return ans;
        int clen=matrix[0].size();
        if(clen==0) return ans;
        int re=rlen-1,ce=clen-1,rs=0,cs=0;
        int rf=0,cf=0;
        while(rs<=re && cs <= ce){
            for(int i=cs;i<=ce;i++){
                if(rs==re) rf=1;
                ans.push_back(matrix[rs][i]);
            }
            for(int i=rs+1;i<=re;i++){
                if(cs==ce) cf=1;
                ans.push_back(matrix[i][ce]);
            }
            for(int i=ce-1;!rf && i>=cs;i--){
                ans.push_back(matrix[re][i]);
            }
            for(int i=re-1;!cf && i>rs;i--){
                ans.push_back(matrix[i][cs]);
            }
            rs++,cs++,re--,ce--;
        }
        return ans;
    }
};
int main(){
    vector<vector<int>> v={{1,2,3,4},{5,6,7,8},{9,10,11,12}};
    Solution s;
    s.spiralOrder(v);


    return 0;
}